<?php
namespace app\mogo\home;

use think\Controller; // 与控制器同名 重命名
use app\mogo\model\User;

class Oauth extends Controller {
    /**
     * 获取用户token
     * 如果是PHP内部使用则使用此方式授权获取mogo_token
     * @param $data
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function auth($data){
        $ip =  $this->request->ip();
        $host = $this->request->host();
//        if($ip!==$host) return json('非法访问',404);
//        $data = request()->only(['openid','nickname','headimgurl']);
//        $openid = $data['openid'];
//        // 如果昵称为空
        if(empty($data['nickname'])) $data['nickname'] = '无昵称';
        // 验证
        $result=$this->validate($data,'User');
        if($result!==true) return json($result,404);
        //判断用户是否存在 不存在则存入
        $user = User::get(['id'=>$data['id']]);
        if(empty($user)) {
            $user  = User::create($data);
        }
        // 生成token 保存进数据库 并返回
        // 每次都会刷新token
        $token = uniqid();
        $user->token = $token;
        // 更新用户
        $user->nickname = $data['nickname'];
        $user->avatar = $data['avatar'];
        $user->save();
        return $user;
    }

    /**
     * 第三方授权获取token
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function oauth(){
        $ip =  $this->request->ip();
        $host = $this->request->host();
//        if($ip!==$host) return json('非法访问',404);
        $data = request()->only(['id','nickname','avatar']);
//        $openid = $data['openid'];
//        // 如果昵称为空
        if(empty($data['nickname'])) $data['nickname'] = '无昵称';
        // 验证
        $result=$this->validate($data,'User');
        if($result!==true) return json($result,404);
        //判断用户是否存在 不存在则存入
        $user = User::get(['id'=>$data['id']]);
        if(empty($user)) {
            $user  = User::create($data);
        }
        // 生成token 保存进数据库 并返回
        // 每次都会刷新token
        $token = uniqid();
        $user->token = $token;
        // 更新用户
        $user->nickname = $data['nickname'];
        $user->avatar = $data['avatar'];
        $user->save();
        return json($user);
    }

    public function test(){
        $res =  $this->auth([
            'id'=>45,
            'nickname'=>'ArH%4',
            'avatar'=>'http://wx.qlogo.cn/mmopen/ERQdplgm8JPpBmTJEJ8sxibtukoTd36PAbibvfD7PxkMtb5sDzcVwiasTIrpjHTCB9SGHmKq1f393mCO0hm1U3eK8PFh7WY1QC2/132'
        ]);
        return $res;
    }

}